﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using KNS.Invoice.UI;
using SQLDMO;
using System.Data.SqlClient;
using DevExpress.Utils;
using System.Runtime.InteropServices;
using InvoiceManagement.Controllers;

namespace InvoiceManagement
{
    public partial class frmSaoLuu : KNSFormBase
    {
        #region "Khai báo biến"
        SQLDMO.ApplicationClass sqlApp = new ApplicationClass();
        SqlConnection sqlConnect;

        public frmSaoLuu()
        {
            InitializeComponent();
        }  
        #endregion

        #region "Các hàm load dữ liệu"
        public void FillListGroupDatabase()
        {
            try
            {
                //ADD CÁC SERVER TRÊN MÁY

                //SQLDMO.ServerGroups groupServer = sqlApp.ServerGroups;
                //if (groupServer.Count > 0)
                //{
                //    foreach (SQLDMO.ServerGroup ite in groupServer)
                //    {
                //        SQLDMO.RegisteredServers itemRes = ite.RegisteredServers;
                //        foreach (SQLDMO.RegisteredServer itemRe in itemRes)
                //        {
                //            this.cboTenMayChu.Properties.Items.Add(itemRe.Name);
                //        }
                //    }
                //}

                //TÌM CÁC SERVER TRONG MẠNG

                //SQLDMO.Application oSQLServerDMOApp = new SQLDMO.Application();
                //SQLDMO.NameList oNameList;
                //oNameList = oSQLServerDMOApp.ListAvailableSQLServers();
                //for (int intIndex = 0; intIndex <= oNameList.Count - 1; intIndex++)
                //{
                //    if (oNameList.Item(intIndex as object) != null)
                //    {
                //        cboTenMayChu.Properties.Items.Add(oNameList.Item(intIndex).ToString());
                //    }
                //    else
                //    {
                //        cboTenMayChu.Properties.Items.Add("(Local)");
                //    }
                //}
                //cboTenMayChu.SelectedIndex = 0;
            }
            catch { }
        }
        #endregion 
             
        #region "Các hàm sự kiện trên form"
        private void frmSaoLuu_Load(object sender, EventArgs e)
        {
            ClearText();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (KiemTraLuuTru())
                {
                    BackupDataBase(txtTenMayServer.Text.ToString(), txtTenDangNhap.Text.ToString(), txtMatKhau.Text.ToString(), txtDuongDan.Text.ToString());
                }
            }
            catch { }
        }

        private void btnChonFile_Click(object sender, EventArgs e)
        {
            try
            {
                folderBrowserDialog1.ShowDialog();
                if (folderBrowserDialog1.SelectedPath.ToString() == "")
                {
                    txtDuongDan.Text = "";
                }
                else
                {
                    txtDuongDan.Text = folderBrowserDialog1.SelectedPath.ToString();
                }
            }
            catch { }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (KiemTraKetNoi())
            {
                DataSet ds = new DataSet();
                SqlCommand sqlCmd = new SqlCommand("sp_Databases", sqlConnect);
                sqlCmd.CommandType = CommandType.Text;
                SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd);
                sqlAdapter.Fill(ds);
                if (ds.Tables.Count > 0)
                {
                    DataTable dt = new DataTable();
                    dt = ds.Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        //DataRow dr;
                        //for (int i = 0; i < dt.Rows.Count ; i++)
                        //{
                        //    cboCSDL.Properties.Items.Add(dt.Rows[i][0].ToString());                              
                        //}
                        cboCSDL.DataSource = dt;
                        cboCSDL.DisplayMember = "Database_name";
                        cboCSDL.ValueMember = "Database_name";
                    }
                    else
                    {
                        cboCSDL.DataSource = null ;
                        cboCSDL.DisplayMember = "Database_name";
                        cboCSDL.ValueMember = "Database_name";
                    }
                }
                else
                {
                    cboCSDL.DataSource = null;
                    cboCSDL.DisplayMember = "Database_name";
                    cboCSDL.ValueMember = "Database_name";
                }
            }
        }
        #endregion

        #region "Các hàm xử lý khác"
        public void ClearText()
        {
            txtTenMayServer.Text = "";
            txtTenDangNhap.Text = "";
            txtMatKhau.Text = "";
            txtTenMayServer.Focus();
        }

        public bool KiemTraDuLieuKetNoi()
        {
            try
            {
                if (txtTenMayServer.Text == string.Empty || txtTenMayServer.Text == "")
                {
                    KNSMessageBox.Show("Chưa nhập tên máy chủ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    txtTenMayServer.Focus();
                    return false;
                }

                if (txtTenDangNhap.Text == string.Empty || txtTenDangNhap.Text == "")
                {
                    KNSMessageBox.Show("Chưa nhập tên đăng nhập", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    txtTenDangNhap.Focus();
                    return false;
                }

                if (txtMatKhau.Text == string.Empty || txtMatKhau.Text == "")
                {
                    KNSMessageBox.Show("Chưa nhập mật khẩu kết nối", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    txtMatKhau.Focus();
                    return false;
                }
                return true;
            }
            catch { return false; }
        }

        public bool KiemTraKetNoi()
        {
            bool bln = false;
            
                string strConnect = "";                
                if (KiemTraDuLieuKetNoi())
                {
                    strConnect = "Server=" + txtTenMayServer.Text.Trim().ToString() + "; UID=" + txtTenDangNhap.Text.Trim().ToString() + "; PWD=" + txtMatKhau.Text.Trim().ToString();
                    sqlConnect = new SqlConnection(strConnect);
                    WaitDialogForm wait = new WaitDialogForm("", "Đang kết nối, vui lòng chờ...");
                    try
                    {
                        sqlConnect.Open();
                        wait.Close();
                        bln = true;
                    }
                    catch {
                        wait.Close();
                        KNSMessageBox.Show("Không thể kết nối", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        ClearText();
                        bln =  false;
                    }
                }
                return bln;
        }

        public bool KiemTraLuuTru()
        {
            try
            {
                if (cboCSDL.Items.Count ==0)                
                {
                    KNSMessageBox.Show("Chưa chọn cơ sở dữ liệu để backup", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    cboCSDL.Focus();
                    return false;
                }

                if (txtDuongDan.Text == string.Empty || txtDuongDan.Text == "")
                {
                    KNSMessageBox.Show("Chưa chọn đường dẫn để backup", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    btnChonFile.Focus();
                    return false;
                }
                return true;
            }
            catch { return false; }
        }

        public void BackupDataBase(string Server_bak, string UserID_bak, string Pass_bak, string Location_bak)
        {
            SQLDMO.SQLServerClass server = new SQLDMO.SQLServerClass();
            SQLDMO.Database database = new SQLDMO.Database();
            SQLDMO.Backup backup = new SQLDMO.Backup();
            try
            {
                //Server login_secure = true                
                server.Connect(Server_bak, UserID_bak, Pass_bak);

                database = (SQLDMO.Database)server.Databases.Item(cboCSDL.Text.ToString(), this);

                //begin - set up event sink
                UCOMIConnectionPointContainer cpContainer;
                cpContainer = (UCOMIConnectionPointContainer)backup;
                UCOMIConnectionPoint cpPoint ;
                clsBackUpSink PES = new clsBackUpSink();
                Guid guid = new Guid("10021F09-E260-11CF-AE68-00AA004A34D5");
                cpContainer.FindConnectionPoint(ref guid, out cpPoint );                
                int intCookie = 0;
                cpPoint.Advise(PES, out intCookie);
                //End - set up events sink


                //Kiểm tra lưu trên ổ đĩa theo thứ tự ưu tiên: D, E, C
                if (System.IO.Directory.Exists("D:\\") == false)
                {
                    if (System.IO.Directory.Exists("E:\\") == true)
                    {
                        //Location_bak = String.Replace(Location_bak, "D:\\", "E:\\");
                        Location_bak = Location_bak.Replace("D:\\", "E:\\");
                    }
                    else
                    {
                        //Location_bak = String.Replace(Location_bak, "D:\\", "C:\\");
                        Location_bak = Location_bak.Replace("D:\\", "C:\\");
                    }
                }

                //Kiểm tra xem có thư mục backup Database chưa, nếu chưa thì tạo thư mục
                if (System.IO.Directory.Exists(Location_bak + "\\Backup" + cboCSDL.Text) == false)
                {
                    System.IO.Directory.CreateDirectory(Location_bak + "\\Backup" + cboCSDL.Text);
                }

                //Kiểm tra xem có thư mục TenCSDL.bak hay không, nếu có thì xoá
                if (System.IO.File.Exists(Location_bak + "\\Backup" + cboCSDL.Text + "\\" + cboCSDL.Text + ".bak") == true)
                {
                    System.IO.File.Delete(Location_bak + "\\Backup" + cboCSDL.Text + "\\" + cboCSDL.Text + ".bak");
                }
                Size size = new Size(300, 50);
                DevExpress.Utils.WaitDialogForm dlg = new DevExpress.Utils.WaitDialogForm("", "Đang backup database,vui lòng chờ...", size);

                try
                {
                    backup.Database = database.Name;
                    backup.Files = Location_bak + "\\Backup" + cboCSDL.Text + "\\" + cboCSDL.Text + ".bak";
                    backup.SQLBackup(server);

                    dlg.Close();

                    cpPoint.Unadvise(intCookie);

                    cpPoint = null;
                    cpContainer = null;
                    PES = null;

                    server.DisConnect();

                    backup = null;
                    server = null;
                    database = null;

                }
                catch (Exception ex)
                {
                    dlg.Close();
                    KNSMessageBox.Show(ex.ToString(), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
            catch (Exception ex)
            {
            }
        }
        #endregion
                      
    }
}